home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
PC World Komputer 2010 April
/
PCWorld0410.iso
/
pluginy Firefox
/
55375
/
55375.xpi
/
components
/
btMetricsLiteService.js
< prev
Wrap
Text File
|
2009-11-15
|
12KB
|
371 lines
const Cc = Components.classes;
const Ci = Components.interfaces;
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
try {
Components.utils.import("resource://gre/modules/JSON.jsm");
JSON.stringify = JSON.toString;
} catch (ex) {
/* Firefox 3.1 has native JSON support */
}
const gPrefService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService);
const gPrefBranch = gPrefService.getBranch(null).QueryInterface(Ci.nsIPrefBranch2);
const gObserver = Cc['@mozilla.org/observer-service;1'].getService(Ci.nsIObserverService);
const gConsoleService = Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService);
const gXULAppInfo = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo);
const gXULRuntime = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime);
const gExtensionManager = Cc["@mozilla.org/extensions/manager;1"].getService(Ci.nsIExtensionManager);
function BTMetricsLite() {
}
BTMetricsLite.prototype = {
debug: false,
serverURI: '',
enabled: false,
bid: '',
browserVersion: 0,
extensionVersion: '',
os: '',
mDBConn: null,
timer: null,
sbServices: {
YAHOO_SB_SERVICE: 1,
ASK_SB_SERVICE: 2
},
request: null,
observe: function(aSubject, aTopic, aData) {
switch(aTopic) {
case "app-startup":
gObserver.addObserver(this,"profile-after-change",false);
gObserver.addObserver(this,"profile-before-change",false);
gObserver.addObserver(this,"xpcom-shutdown",false);
gObserver.addObserver(this,"final-ui-startup",false);
break;
case "xpcom-shutdown":
gObserver.removeObserver(this,"profile-after-change");
gObserver.removeObserver(this,"profile-before-change");
gObserver.removeObserver(this,"final-ui-startup");
gObserver.removeObserver(this,"xpcom-shutdown");
break;
case "profile-before-change":
this.packageData(false);
break;
case "final-ui-startup":
gObserver.addObserver(this, "brandthunder", false);
this.init();
break;
case "brandthunder":
var currentBoom = "";
try {
currentBoom = this.getPref('extensions.brandthunder.currentBoom');
} catch (ex) {}
var brandObject = aSubject.wrappedJSObject;
/* Need to accomodate old code */
if (brandObject.booms) {
/* If the currentBoom isn't in the brand Object we were given, */
/* use the client short name */
if (!brandObject.booms[currentBoom]) {
currentBoom = brandObject.shortName;
}
}
if (aData == "active") {
this.extensionVersion = gExtensionManager.getItemForID(brandObject.extensionID).version;
this.sendActiveStatus(currentBoom);
} else {
this.storeAction(currentBoom, aData);
}
return;
}
},
notify: function(timer) {
this.packageData(true);
},
init: function() {
var env = Cc['@mozilla.org/process/environment;1'].getService(Ci.nsIEnvironment);
if (env.get('BRANDTHUNDER')) {
this.debug = true;
}
this.enabled = this.getPref('extensions.btMetricsLite.enabled');
this.serverURI = this.getPref('extensions.btMetricsLite.uri');
var env = Cc['@mozilla.org/process/environment;1'].getService(Ci.nsIEnvironment);
if (this.debug) {
this.serverURI = 'https://btmetrics-dev.brandthunder.com/service';
}
if (!this.getPref('extensions.btMetricsLite.bid')) {
this.setPref('extensions.btMetricsLite.bid', this.generateBid());
}
this.bid = this.getPref('extensions.btMetricsLite.bid');
this.browserVersion = gXULAppInfo.version.match(/(\d+\.\d+)/)[1].replace('.', '');
this.os = gXULRuntime.OS;
this.timer = Components.classes['@mozilla.org/timer;1'].createInstance(Components.interfaces.nsITimer);
if (this.debug) {
this.timer.initWithCallback(this, 30000, Components.interfaces.nsITimer.TYPE_REPEATING_SLACK);
} else {
this.timer.initWithCallback(this, 300000, Components.interfaces.nsITimer.TYPE_REPEATING_SLACK);
}
var database = Components.classes['@mozilla.org/file/directory_service;1']
.getService(Components.interfaces.nsIProperties)
.get('ProfD', Components.interfaces.nsIFile);
database.append('btmetricslite.sqlite');
this.mDBConn = Components.classes['@mozilla.org/storage/service;1'].getService(Components.interfaces.mozIStorageService).openDatabase(database);
this.sqlToObj("CREATE TABLE IF NOT EXISTS 'events' ('cid' VARCHAR(255) NOT NULL, 'action' VARCHAR(255) NOT NULL, 'created' DATETIME NOT NULL)");
},
getPref: function(name, defaultVal) {
try {
switch (gPrefBranch.getPrefType(name)) {
case 32: //string
return gPrefBranch.getCharPref(name);
case 64: //int
return gPrefBranch.getIntPref(name);
case 128: //bool
return gPrefBranch.getBoolPref(name);
}
} catch (e) {
}
return defaultVal;
},
setPref: function(name, val) {
if ((val === true) || (val === false)){
gPrefBranch.setBoolPref(name, val);
} else if (typeof val == 'string'){
gPrefBranch.setCharPref(name, val);
} else {
gPrefBranch.setIntPref(name, val);
}
},
md5: function(str) {
var converter = Cc['@mozilla.org/intl/scriptableunicodeconverter'].createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = 'UTF-8';
var result = {};
var data = converter.convertToByteArray(str, result);
var ch = Cc['@mozilla.org/security/hash;1'].createInstance(Ci.nsICryptoHash);
ch.init(ch.MD5);
ch.update(data, data.length);
var hash = ch.finish(false);
function toHexString(charCode) {
return ('0' + charCode.toString(16)).slice(-2);
}
var s = [toHexString(hash.charCodeAt(i)) for (i in hash)].join('');
return s;
},
timestamp: function(_131) {
var d = new Date();
var _133 = d.getTime();
var time = _133/1000;
var _135 = parseInt(time);
return (_131) ? time : _135;
},
generateBid: function() {
return this.md5(this.timestamp(true) + ':' + Math.random());
},
storeAction: function(shortName, action) {
if (this.enabled) {
var localdate = new Date();
try {
this.sqlToObj("INSERT INTO events " +
"(cid, action, created) " +
"VALUES " +
"('" + this.dbClean(shortName) + "', '" + this.dbClean(action) + "', '" + this.toTimeString(localdate) + "')");
} catch (e) {}
}
},
sendActiveStatus: function(currentBoom) {
var currentdate = new Date();
var currenttimestamp = currentdate.getTime() / 1000;
var lastsent = this.getPref('extensions.btMetricsLite.lastsent');
if (lastsent) {
if ((currenttimestamp - lastsent) < 3600) {
if (!this.debug) {
return;
}
}
}
var searchSvc = Cc['@mozilla.org/browser/search-service;1']
.getService(Ci.nsIBrowserSearchService);
if (searchSvc.currentEngine.description == "Yahoo! - BT") {
searchService = this.sbServices.YAHOO_SB_SERVICE;
} else if (searchSvc.currentEngine.description == "Ask - BT") {
searchService = this.sbServices.ASK_SB_SERVICE;
} else {
searchService = 0;
}
this.sendData('active=1&cid=' + currentBoom + '&bid=' + this.bid + '&bv=' + this.browserVersion + '&os=' + this.os + '&ev=' + this.extensionVersion + '&sbs=' + searchService, false, true);
this.setPref('extensions.btMetricsLite.lastsent', currenttimestamp);
},
toTimeString: function(localdate) {
return this.toDateString(localdate, 'y-m-d h:i:s', true);
},
toDateString: function(localdate, format, showZeros) {
var gmt = localdate.getTime() + (localdate.getTimezoneOffset() * 60000);
var date = new Date(gmt);
format = format.toLowerCase();
// cast all values to strings
var day = '' + date.getDate(),
month = '' + (date.getMonth() + 1),
hour = '' + date.getHours(),
minute = '' + date.getMinutes(),
second = '' + date.getSeconds(),
year = '' + date.getFullYear();
// pad leading zeros
if (showZeros) {
if (1 === day.length) {day = '0' + day;}
if (1 === month.length) {month = '0' + month;}
if (1 === hour.length) {hour = '0' + hour;}
if (1 === minute.length) {minute = '0' + minute;}
if (1 === second.length) {second = '0' + second;}
}
return format.replace('y', year)
.replace('d', day)
.replace('h', hour)
.replace('i', minute)
.replace('s', second)
.replace('m', month); // do month last as some months contain reserved letters
},
clearTime: function(date) {
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
},
packageData: function(async) {
var dbObject = this.sqlToObj("SELECT * FROM events");
if (dbObject.length > 0) {
jsonString = JSON.stringify(dbObject);
var this_ptr = this;
this.sendData('bid=' + this.bid + '&ev=' + this.extensionVersion + '&events=' + jsonString, function(responseText) {
this_ptr.sqlToObj("DELETE FROM events");
}, async);
//temporary measure to make sure that the sqllite db is cleared on browser close
if (!async) {
this.sqlToObj("DELETE FROM events");
}
}
},
sendData: function(data, callback, async) {
this.request = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
this.request.onreadystatechange = function() {
if (this.readyState == 4) {
if (callback) {
callback(this.responseText);
}
}
};
this.request.open('POST', this.serverURI, async);
this.request.setRequestHeader('Connection', 'close');
this.request.setRequestHeader('Keep-Alive', '');
this.request.setRequestHeader('Content-Length', data.length);
this.request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
this.request.send(data);
},
sqlToObj: function(sql, matches) {
var rs, error = false, eMessage;
if (matches == null) {
matches = [];
}
var i, cols, ret, row = 0;
ret = [];
var statement = this.mDBConn.createStatement(sql);
var binds = false;
while (matches.length > 0) {
binds = true;
thisMatch = matches.pop();
if (thisMatch[0] == 'UTF8String') {
statement.bindUTF8StringParameter(matches.length, thisMatch[2]);
} else if (thisMatch[0] == 'Int32') {
statement.bindInt32Parameter(matches.length, thisMatch[2]);
} else if (thisMatch[0] == 'Blob') {
statement.bindBlobParameter(matches.length, thisMatch[2]);
}
}
while (statement.executeStep()) {
cols = statement.columnCount;
ret[row] = new Object();
for (i = 0; i < cols; i++) {
var mytype = statement.getTypeOfIndex(i);
var myval;
if (mytype == statement.VALUE_TYPE_NULL) {
myval = statement.getIsNull(i);
} else if (mytype == statement.VALUE_TYPE_INTEGER) {
myval = statement.getInt32(i);
} else if (mytype == statement.VALUE_TYPE_FLOAT) {
myval = statement.getDouble(i);
} else if (mytype == statement.VALUE_TYPE_TEXT) {
myval = statement.getUTF8String(i);
} else if (mytype == statement.VALUE_TYPE_BLOB) {
myval = statement.getBlob(i);
} else {
myval = null;
}
ret[row][statement.getColumnName(i)] = myval;
}
row++;
}
statement.reset();
statement = null;
return ret;
},
dbClean: function(str) {
var pairs = [["'", "''"]];
for (var i = 0; i < pairs.length; i++) {
str = str.split(pairs[i][0]).join(pairs[i][1]);
}
return str;
},
log: function(string) {
gConsoleService.logStringMessage(string);
},
classDescription: "Brand Thunder Metrics Lite",
contractID: "@brandthunder.com/btmetricslite;1",
classID: Components.ID("{5b578c72-d669-4ea9-8d9a-d049d6ade22c}"),
QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsITimerCallback]),
_xpcom_categories: [{
category: "app-startup",
service: true
}]
}
function NSGetModule(compMgr, fileSpec) {
return XPCOMUtils.generateModule([BTMetricsLite]);
}